﻿Imports System.Timers
Imports KeyMonitor.LockManager

Public Class Main

    Protected Overrides Sub OnStart(ByVal args() As String)
        Dim man = New LockManagerClient()
        _AbortTime = man.GetAbortTime()
        _KeyCheckTime = man.GetKeyCheck()
        _PanicFilePath = man.GetPanicFilePath()
        _Timer = New Timer()
        _Timer.Interval = _KeyCheckTime * 1000
        AddHandler _Timer.Elapsed, AddressOf Me.DoWork
        _Timer.Start()
    End Sub

    Protected Overrides Sub OnStop()
        If _Timer Is Nothing Then
            Throw New Exception("Unable to stop windows service. Please call StartService first.")
        Else
            _Timer.Stop()
        End If
    End Sub

    Public Sub DoWork(ByVal sender As Object, ByVal e As ElapsedEventArgs)
        _Timer.Enabled = False
        Dim man = New LockManagerClient()
        man.ShowKeypad()
        _TerminatorTimer = New Timer()
        _TerminatorTimer.Interval = _AbortTime * 1000
        AddHandler _TerminatorTimer.Elapsed, AddressOf Me.ExecutePanicBatch
        _TerminatorTimer.Start()
        '_Timer.Enabled = True
    End Sub

    Private Sub ExecutePanicBatch(ByVal sender As Object, ByVal e As ElapsedEventArgs)
        Dim man = New LockManagerClient()        
        If Not man.GetStatus() Then
            Using batchExecute As New Process
                Dim batchExecuteInfo As New ProcessStartInfo(_PanicFilePath)
                batchExecuteInfo.UseShellExecute = False
                batchExecuteInfo.CreateNoWindow = True
                batchExecute.StartInfo = batchExecuteInfo
                batchExecute.Start()

                'Set the period of time to wait for the associated
                'process to exit, and blocks the current thread
                'until the time has elapsed or the
                'process has exited
                batchExecute.WaitForExit(300000)

                If batchExecute.ExitCode > 0 And Not batchExecute.HasExited Then
                    batchExecute.Kill()
                End If
            End Using
        End If
        _TerminatorTimer.Enabled = False
    End Sub

    Private _Timer As Timer
    Private _TerminatorTimer As Timer
    Private _PanicFilePath As String
    Private _AbortTime As Integer
    Private _KeyCheckTime As Integer

End Class
